import { getToken, setToken, removeToken } from "@/utils/auth";
import { login, getUserInfo } from "@/api/user";
import { constantRoutes } from "@/router";
const state = {
  token: getToken(), //从缓存中读取初始值
  // 存储用户资料状态
  userInfo: {},
  routes: constantRoutes, // 新增
};

const mutations = {
  setToken(state, token) {
    state.token = token;
    // 同步到缓存
    setToken(token);
  },
  removeToken() {
    state.token = null;
    removeToken();
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes];
  },
};

const actions = {
  // context传入参数
  async login(context, data) {
    console.log(data);
    // todo: 调用登录接口
    const token = await login(data);
    //返回一个token
    context.commit("setToken", token);
  },
  clearCache({ commit }) {
    commit("removeToken");
    console.log("清除缓存");
  },
  async getUserInfo(context) {
    const result = await getUserInfo();
    console.log(result);
    context.commit("setUserInfo", result);
    return result;
  },
  logout(context) {
    context.commit("removeToken");
    context.commit("setUserInfo", {});
  },
};

export default {
  namespaced: true, //开启命名空间
  state,
  mutations,
  actions,
};
